package com.changpay.zywy.wight


import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import com.changpay.zywy.R
import com.changpay.zywy.utils.DensityUtils

import android.graphics.Paint.Style.FILL
import android.graphics.Paint.Style.STROKE

/**
 *
 */

class CustomCircleProgressBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    var outsideColor: Int = 0    //进度的颜色
    var outsideRadius: Float = 0.toFloat()    //外圆半径大小N
        var insideColor: Int = 0    //背景颜色
    var progressTextColor: Int = 0   //圆环内文字颜色
    var progressTextSize: Float = 0.toFloat()    //圆环内文字大小
    var progressWidth: Float = 0.toFloat()    //圆环的宽度
    private var maxProgress: Int = 0    //最大进度
    @get:Synchronized
    var progress: Float = 0.toFloat()
        private set    //当前进度
    private val direction: Int    //进度从哪里开始(设置了4个值,上左下右)
    private var progress_text: String? = null

    private val paint: Paint
    private var progressText: String? = null     //圆环内文字
    private var rect: Rect? = null

    private val animator: ValueAnimator? = null

    internal enum class DirectionEnum private constructor(val direction: Int, val degree: Float) {
        LEFT(0, 180.0f),
        TOP(1, 270.0f),
        RIGHT(2, 0.0f),
        BOTTOM(3, 90.0f);

        fun equalsDescription(direction: Int): Boolean {
            return this.direction == direction
        }

        companion object {

            fun getDirection(direction: Int): DirectionEnum {
                for (enumObject in values()) {
                    if (enumObject.equalsDescription(direction)) {
                        return enumObject
                    }
                }
                return RIGHT
            }

            fun getDegree(direction: Int): Float {
                val enumObject = getDirection(direction) ?: return 0f
                return enumObject.degree
            }
        }
    }

    init {
        val a = context.theme.obtainStyledAttributes(attrs, R.styleable.CustomCircleProgressBar, defStyleAttr, 0)
        outsideColor = a.getColor(
            R.styleable.CustomCircleProgressBar_outside_color,
            ContextCompat.getColor(getContext(), R.color.colorPrimary)
        )
        outsideRadius = a.getDimension(
            R.styleable.CustomCircleProgressBar_outside_radius,
            DensityUtils.dip2px(getContext(), 60.0f).toFloat()
        )
        insideColor = a.getColor(
            R.styleable.CustomCircleProgressBar_inside_color,
            ContextCompat.getColor(getContext(), R.color.inside_color)
        )
        progressTextColor = a.getColor(
            R.styleable.CustomCircleProgressBar_progress_text_color,
            ContextCompat.getColor(getContext(), R.color.colorPrimary)
        )
        progressTextSize = a.getDimension(
            R.styleable.CustomCircleProgressBar_progress_text_size,
            DensityUtils.dip2px(getContext(), 14.0f).toFloat()
        )
        progressWidth = a.getDimension(
            R.styleable.CustomCircleProgressBar_progress_width,
            DensityUtils.dip2px(getContext(), 10.0f).toFloat()
        )
        progress = a.getFloat(R.styleable.CustomCircleProgressBar_progress, 50.0f)
        maxProgress = a.getInt(R.styleable.CustomCircleProgressBar_max_progress, 100)
        direction = a.getInt(R.styleable.CustomCircleProgressBar_direction, 3)

        a.recycle()
        paint = Paint()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 第步:画背景
        val circlePoint = width / 2
        paint.color = Color.parseColor("#FFFFFF") //设置圆的颜色
        paint.style = FILL //设置实心圆
        paint.strokeWidth = circlePoint.toFloat() //设置圆的宽度
        paint.isAntiAlias = true  //消除锯齿
        canvas.drawCircle(circlePoint.toFloat(), circlePoint.toFloat(), circlePoint.toFloat(), paint) //画出圆

        //第一步:内层圆
        paint.color = insideColor //设置圆的颜色
        paint.style = STROKE //设置空心
        paint.strokeWidth = progressWidth //设置圆的宽度
        paint.isAntiAlias = true  //消除锯齿
        canvas.drawCircle(circlePoint.toFloat(), circlePoint.toFloat(), outsideRadius, paint) //画出圆

        //第二步:画进度(圆弧)
        paint.color = outsideColor  //设置进度的颜色
        val oval = RectF(
            circlePoint - outsideRadius,
            circlePoint - outsideRadius,
            circlePoint + outsideRadius,
            circlePoint + outsideRadius
        )  //用于定义的圆弧的形状和大小的界限
        canvas.drawArc(
            oval,
            DirectionEnum.getDegree(direction),
            360 * (progress / maxProgress),
            false,
            paint
        )  //根据进度画圆弧

        //第三步:画圆环内百分比文字
        rect = Rect()
        paint.color = progressTextColor
        paint.textSize = progressTextSize
        paint.strokeWidth = 0f
        progressText = getProgressText()
        paint.getTextBounds(progressText, 0, progressText!!.length, rect)
        val fontMetrics = paint.fontMetricsInt
        val baseline = (measuredHeight - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top  //获得文字的基准线
        canvas.drawText(progressText!!, (measuredWidth / 2 - rect!!.width() / 2).toFloat(), baseline.toFloat(), paint)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width: Int
        val height: Int
        var size = View.MeasureSpec.getSize(widthMeasureSpec)
        var mode = View.MeasureSpec.getMode(widthMeasureSpec)

        if (mode == View.MeasureSpec.EXACTLY) {
            width = size
        } else {
            width = (2 * outsideRadius + progressWidth).toInt()
        }
        size = View.MeasureSpec.getSize(heightMeasureSpec)
        mode = View.MeasureSpec.getMode(heightMeasureSpec)
        if (mode == View.MeasureSpec.EXACTLY) {
            height = size
        } else {
            height = (2 * outsideRadius + progressWidth).toInt()
        }
        setMeasuredDimension(width, height)
    }

    //中间的进度百分比
    private fun getProgressText(): String? {
        return if (TextUtils.isEmpty(progress_text)) {
            (progress / maxProgress * 100).toInt().toString() + "%"
        } else {
            progress_text
        }

    }

    fun setProgressText(text: String) {
        progress_text = text
    }

    @Synchronized
    fun getMaxProgress(): Int {
        return maxProgress
    }

    @Synchronized
    fun setMaxProgress(maxProgress: Int) {
        if (maxProgress < 0) {
            //此为传递非法参数异常
            throw IllegalArgumentException("maxProgress should not be less than 0")
        }
        this.maxProgress = maxProgress
    }

    //加锁保证线程安全,能在线程中使用
    @Synchronized
    fun setProgress(progress: Int) {
        var progress = progress
        if (progress < 0) {
            throw IllegalArgumentException("progress should not be less than 0")
        }
        if (progress > maxProgress) {
            progress = maxProgress
        }
        startAnim(progress.toFloat())
    }

    private fun startAnim(startProgress: Float) {
        this@CustomCircleProgressBar.progress = startProgress
        postInvalidate()
        //        animator = ObjectAnimator.ofFloat(0, startProgress);
        //        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        //            @Override
        //            public void onAnimationUpdate(ValueAnimator animation) {
        //                = (float) animation.getAnimatedValue();
        //
        //            }
        //        });
        //        animator.setStartDelay(500);
        //        animator.setDuration(2000);
        //        animator.setInterpolator(new LinearInterpolator());
        //        animator.start();
    }
}